package com.kvest.bookprovider;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 22.04.13
 * Time: 21:09
 * To change this template use File | Settings | File Templates.
 */
public class BooksListActivity extends Activity {
    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.books_list_layout);
        Log.d("Kvest", "Create BooksListActivity");
        ListView listView = (ListView) findViewById(R.id.books_list_view);
        initListView(listView);
    }

    private void initListView(ListView listView) {

        String[] projection = new String[]{BookProviderMetaData.BookTableMetaData._ID, BookProviderMetaData.BookTableMetaData.BOOK_NAME, BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR};
        Uri uri = BookProviderMetaData.BookTableMetaData.CONTENT_URI;
        Cursor cursor = managedQuery(uri, projection ,null,null,null);

        // формируем столбцы сопоставления
        String[] from = new String[] {BookProviderMetaData.BookTableMetaData.BOOK_NAME, BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR};
        int[] to = new int[] { R.id.book_name, R.id.book_author };

        // создааем адаптер и настраиваем список
        SimpleCursorAdapter scAdapter = new SimpleCursorAdapter(this, R.layout.listitem, cursor, from, to);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(), "i=" + i + ", l=" + l, Toast.LENGTH_SHORT).show();
            }
        });
        listView.setAdapter(scAdapter);
    }

    public void onEditClick(View view) {
        Intent intent = new Intent(getApplicationContext(), BookActivity.class);
        startActivity(intent);
    }
}
